﻿using RMS.EF.Model;
using RMS.EF.Model.Common;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace RMS.BLL
{
    public class RoleBll
    {

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">分页参数</param>
        /// <param name="searchValue">搜索框</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public List<RMS_Role> GetByPage(PageParams page, string searchValue, E_Status status)
        {
            List<RMS_Role> result = new List<RMS_Role>();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Role.Where(p => p.Deleted == (int)E_Deleted.Normal);
                #region where
                if (!string.IsNullOrWhiteSpace(searchValue))
                {
                    q = q.Where(p => p.Name.Contains(searchValue));
                }
                if (status != E_Status.All)
                {
                    q = q.Where(p => p.Status == (int)status);
                }
                #endregion
                page.Total = q.Count();
                #region order by
                if (string.IsNullOrWhiteSpace(page.Order))
                {
                    q = q.OrderBy(p => p.Ordering);
                }
                else
                {
                    var orderExpression = string.Format("{0} {1}", page.Order, page.OrderType);
                    q = q.OrderBy(orderExpression);
                }
                #endregion
                q = q.Skip(page.Start).Take(page.Length);
                result = q.ToList();
            }
            return result;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id">数据Id字符串","分隔</param>
        /// <returns></returns>
        public CommonOutPutVm Delete(string id)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                db.Database.ExecuteSqlCommand("update RMS_Role set Deleted=1 where Id in (" + id + ")");
                db.SaveChanges();
            }
            result.IsSuccess = true;
            result.Message = "Delete success";
            return result;
        }
        /// <summary>
        /// 根据Id获取未删除的实体
        /// </summary>
        /// <param name="id">Id主键</param>
        /// <returns></returns>
        public RMS_Role GetById(string id)
        {
            RMS_Role result = new RMS_Role();
            using (var db = new RMSEntities())
            {
                result = db.RMS_Role.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
            }
            return result;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">编辑后的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Edit(RMS_Role model)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                bool exist = db.RMS_Role.Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && p.Name == model.Name);
                if (exist)
                    throw new Exception("Name already exists");
                db.RMS_Role.Attach(model);
                db.Entry(model).State = !string.IsNullOrWhiteSpace(model.Id) ? EntityState.Modified : EntityState.Added;
                int row = db.SaveChanges();
                if (row != 1)
                    throw new Exception("Save failed");
                result.IsSuccess = true;
                result.Message = "Save success";
            }
            return result;
        }
        /// <summary>
        /// 关联菜单
        /// </summary>
        /// <param name="id">角色Id</param>
        /// <param name="menuId">菜单Id集合</param>
        /// <param name="programId">项目Id</param>
        /// <param name="userId">操作用户Id</param>
        /// <returns></returns>
        public CommonOutPutVm Relation_Menu(string id, List<string> menuId, string programId, string userId)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        DateTime now = DateTime.Now;
                        #region 根据角色Id删除所有关联
                        string sql = @"update rm set rm.Deleted=1, rm.LastUpdateTime=@now, rm.LastUpdateUser=@userId
from RMS_Role_Menu rm left join RMS_Menu m on rm.MenuId=m.Id
where rm.RoleId=@id and m.ProgramId=@programId";
                        db.Database.ExecuteSqlCommand(sql,
                            new SqlParameter("@id", id),
                            new SqlParameter("@now", now),
                            new SqlParameter("@userId", userId),
                            new SqlParameter("@programId", programId));
                        db.SaveChanges();
                        #endregion
                        #region 循环处理
                        for (int i = 0; i < menuId.Count; i++)
                        {
                            var item = menuId[i];
                            //存在验证
                            var exist = db.RMS_Role_Menu.Any(p => p.RoleId == id && p.MenuId == item);
                            #region 存在就修改删除标记
                            if (exist)
                            {
                                sql = @"update RMS_Role_Menu set Deleted=0, LastUpdateTime=@now, LastUpdateUser=@userId where RoleId=@id and MenuId=@menuId";
                                db.Database.ExecuteSqlCommand(sql,
                                    new SqlParameter("@id", id),
                                    new SqlParameter("@menuId", item),
                                    new SqlParameter("@now", now),
                                    new SqlParameter("@userId", userId));
                            }
                            #endregion
                            #region 不存在就新增记录
                            else
                            {
                                var model = new RMS_Role_Menu()
                                {
                                    RoleId = id,
                                    MenuId = item,
                                    Deleted = (int)E_Deleted.Normal,
                                    CreationTime = now,
                                    CreationUser = userId,
                                    LastUpdateTime = now,
                                    LastUpdateUser = userId
                                };
                                db.RMS_Role_Menu.Add(model);
                            }
                            #endregion
                            db.SaveChanges();
                        }
                        #endregion
                        tran.Commit();
                        result.IsSuccess = true;
                        result.Message = "Save success";
                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                        throw e;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 根据角色获取菜单关联信息
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <returns></returns>
        public List<RMS_Role_Menu> Get_RoleMenu_ByRoleId(string roleId)
        {
            List<RMS_Role_Menu> result = new List<RMS_Role_Menu>();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Role_Menu.Where(p => p.Deleted == (int)E_Deleted.Normal
                && p.RoleId==roleId).OrderBy(p=>p.MenuId);
                result = q.ToList();
            }
            return result;
        }
        /// <summary>
        /// 获取所有可用角色
        /// </summary>
        /// <returns></returns>
        public CommonOutPutVm GetAllEnable()
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Role.Where(p => p.Deleted == (int)E_Deleted.Normal && p.Status == (int)E_Status.Enable).OrderBy(p => p.Ordering);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
    }
}
